package com.jago.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = "D:\\Program Files (x86)\\IDEA-2020.3.4\\workspace\\java-web\\javaweb-04-response\\src\\main\\resources\\机械革命.png";
        System.out.println("下载文件的路径：" + realPath);
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
        // 设置网页文件下载的header
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        FileInputStream fi = new FileInputStream(realPath);
        int len = 0;
        byte[] buff = new byte[1024];
        ServletOutputStream outputStream = resp.getOutputStream();
        while ((len = fi.read(buff)) > 0) {
            outputStream.write(buff, 0, len);
        }
        fi.close();
        outputStream.close();
    }
}
